package com.jsoft.jsofted.sys.vo;

import com.jsoft.jsofted.sys.entity.OrgEntity;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

public class OrgTreeMaker {
    private List<OrgEntity> entityList;

    private LinkedHashMap<Long, OrgBean> nodes;

    private List<OrgBean> tree;

    private OrgTreeMaker(List<OrgEntity> list) {
        this.entityList = list;
    }

    public static List<OrgBean> make(List<OrgEntity> list) {
        OrgTreeMaker maker = new OrgTreeMaker(list);
        maker._makeNodes();
        maker._makeTree();
        return maker.tree;
    }

    private void _makeNodes() {
        this.nodes = new LinkedHashMap();
        for (OrgEntity entity : entityList) {
            OrgBean node = new OrgBean();
            node.copyFrom(entity);
            this.nodes.put(entity.getId(), node);
        }
    }

    private void _makeTree() {
        this.tree = new LinkedList();
        for (OrgEntity entity : entityList) {
            OrgBean node = this.nodes.get(entity.getId());
            OrgBean parentNode = this.nodes.get(node.getParentId());

            if (parentNode == null) {
                this.tree.add(node);
            } else {
                parentNode.addChild(node);
            }
        }
    }

}
